pipeline {
    agent any

    parameters {
        gitParameter name: 'BRANCH',
                    type: 'PT_BRANCH',
                    defaultValue: 'origin/master',
                    description: '选择要构建的分支',
                    branchFilter: 'origin/(master|.*)',
                    sortMode: 'DESCENDING_SMART',
                    useRepository: 'git@gitee.com:tianyuanoss/anypay.git',
                    selectedValue: 'TOP',
                    listSize: '10'
        choice(name: 'ENV',
               choices: ['dev', 'test', 'prod'],
               description: '选择部署环境')
        string(name: 'VERSION',
               defaultValue: '',
               description: '版本号（可选，留空则自动生成）')
    }

    environment {
        PATH = "/opt/homebrew/bin:/opt/homebrew/opt/mysql@8.0/bin:/Users/tianyuan02/.nvm/versions/node/v18.20.3/bin:${env.PATH}"
        GIT_ROOT = "/Users/tianyuan02/.jenkins/workspace/anypay-pipeline/anypay"
        // 部署路径配置
        BACKEND_DEPLOY_PATH = "/Users/tianyuan02/bera"
        FRONTEND_DEPLOY_PATH = "/var/www/html/hainei"
        ARTIFACTS_BACKUP_PATH = "/Users/tianyuan02/bera/artifacts"
        // 构建产物名称
        BACKEND_ARTIFACT_NAME = ""
        FRONTEND_ARTIFACT_NAME = ""
        // 构建产物名称文件
        ARTIFACT_NAMES_FILE = "${WORKSPACE}/artifact_names.env"
        // 构建参数
        BUILD_ENV = "${params.ENV}"
        BUILD_VERSION = "${params.VERSION}"
    }

    stages {
        stage('打印参数信息') {
            steps {
                echo "=== Build Parameters ==="
                echo "Branch: ${params.BRANCH}"
                echo "Environment: ${params.ENV}"
                echo "Version: ${params.VERSION}"
                echo "Workspace: ${WORKSPACE}"
                echo "======================="
            }
        }

        stage('清理和检出代码') {
            steps {
                // 清理工作目录
                sh '''
                    rm -rf $WORKSPACE/*
                    rm -f ${ARTIFACT_NAMES_FILE}
                '''

                // 检出 berabuild
                dir('berabuild') {
                    git url: 'git@gitee.com:tianyuanx/berabuild.git', branch: "${params.BRANCH}"
                    sh 'git clean -fdx'
                }

                // 检出 anypay
                dir('anypay') {
                    git url: 'git@gitee.com:tianyuanoss/anypay.git', branch: "${params.BRANCH}"
                    sh 'git clean -fdx'
                }

                // 显示目录结构
                sh 'echo "=== Directory Structure ===" && ls -la $WORKSPACE'

                // 显示分支信息
                sh '''
                    echo "=== berabuild Branch Info ==="
                    cd $WORKSPACE/berabuild
                    git branch -a

                    echo "=== anypay Branch Info ==="
                    cd $WORKSPACE/anypay
                    git branch -a
                '''
            }
        }

        stage('检查环境') {
            steps {
                sh '''
                    export LANG=C.UTF-8
                    export LC_ALL=C.UTF-8

                    # 定义中文输出函数
                    log_cn() {
                        printf "%s\n" "$1"
                    }

                    log_cn "=== Node.js 版本 ==="
                    which node
                    node --version
                    echo "=== npm 版本 ==="
                    which npm
                    npm --version
                    echo "=== Maven 版本 ==="
                    which mvn
                    mvn --version
                    echo "=== Redis 版本 ==="
                    if ! which redis-cli > /dev/null; then
                        echo "错误: Redis 客户端未安装"
                        exit 1
                    fi
                    redis-cli --version
                    echo "=== Redis 连接测试 ==="
                    if ! redis-cli ping > /dev/null; then
                        echo "错误: Redis 连接失败"
                        exit 1
                    fi
                    echo "Redis 连接成功"
                    echo "=== MySQL 客户端路径 ==="
                    which mysql
                    echo "=== MySQL 版本 ==="
                    if ! which mysql > /dev/null; then
                        echo "错误: MySQL 客户端未安装"
                        exit 1
                    fi
                    mysql --version
                    echo "=== MySQL 连接测试 ==="
                    if ! mysql -u root -p123456 -e "SELECT 'MySQL连接成功!' as result;" > /dev/null 2>&1; then
                        echo "错误: MySQL 连接失败，请检查服务状态和密码"
                        exit 1
                    fi
                    echo "MySQL 连接成功"
                '''
            }
        }

        stage('准备Python环境') {
            steps {
                dir('berabuild') {
                    sh '''
                        if [ ! -d "venv" ]; then
                            echo "开始创建Python虚拟环境..."
                            python3 -m venv venv > python_env.log 2>&1
                            source venv/bin/activate
                            echo "升级pip..."
                            python3 -m pip install --upgrade pip >> python_env.log 2>&1
                            echo "配置pip镜像源..."
                            pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple >> python_env.log 2>&1
                            echo "安装依赖包..."
                            pip3 install -r requirements.txt >> python_env.log 2>&1
                            echo "Python环境准备完成"
                        else
                            source venv/bin/activate
                            echo "使用已存在的Python虚拟环境"
                        fi
                    '''
                }
            }
        }

        stage('构建AnyPay后端项目') {
            steps {
                dir('berabuild') {
                    sh '''
                        source venv/bin/activate
                        echo "使用环境配置: $BUILD_ENV"
                        if [ -n "$BUILD_VERSION" ]; then
                            echo "使用指定版本: $BUILD_VERSION"
                            python3 bera.py build-spring-anypay --config $BUILD_ENV --version $BUILD_VERSION
                        else
                            echo "使用自动生成版本"
                            python3 bera.py build-spring-anypay --config $BUILD_ENV
                        fi
                        # 保存后端构建产物名称
                        export BACKEND_ARTIFACT_NAME=$(find . -name "anypay_*.tar.gz" | sort -r | head -n 1 | xargs basename)
                        echo "BACKEND_ARTIFACT_NAME=${BACKEND_ARTIFACT_NAME}" >> ${ARTIFACT_NAMES_FILE}
                    '''
                }
            }
        }

        stage('构建AnyPay前端项目') {
            steps {
                dir('berabuild') {
                    sh '''
                        source venv/bin/activate
                        echo "使用环境配置: $BUILD_ENV"
                        if [ -n "$BUILD_VERSION" ]; then
                            echo "使用指定版本: $BUILD_VERSION"
                            python3 bera.py anypay-manager-ui --config $BUILD_ENV --version $BUILD_VERSION
                        else
                            echo "使用自动生成版本"
                            python3 bera.py anypay-manager-ui --config $BUILD_ENV
                        fi
                        # 保存前端构建产物名称
                        export FRONTEND_ARTIFACT_NAME=$(find . -name "anypay-manager-ui_*.tar.gz" | sort -r | head -n 1 | xargs basename)
                        echo "FRONTEND_ARTIFACT_NAME=${FRONTEND_ARTIFACT_NAME}" >> ${ARTIFACT_NAMES_FILE}
                    '''
                }
            }
        }

        stage('部署和备份') {
            steps {
                sh '''
                    # 加载构建产物名称
                    if [ -f ${ARTIFACT_NAMES_FILE} ]; then
                        source ${ARTIFACT_NAMES_FILE}
                    else
                        echo "未找到构建产物名称文件"
                        exit 1
                    fi

                    # 创建备份目录
                    mkdir -p ${ARTIFACTS_BACKUP_PATH}

                    # 处理后端部署
                    echo "开始部署后端..."
                    if [ -n "$BACKEND_ARTIFACT_NAME" ] && [ -f "${WORKSPACE}/berabuild/artifacts/$BACKEND_ARTIFACT_NAME" ]; then
                        # 备份制品
                        cp "${WORKSPACE}/berabuild/artifacts/$BACKEND_ARTIFACT_NAME" "${ARTIFACTS_BACKUP_PATH}/"

                        # 直接解压到目标目录
                        tar -xzf "${WORKSPACE}/berabuild/artifacts/$BACKEND_ARTIFACT_NAME" -C "${BACKEND_DEPLOY_PATH}"

                        # 重启服务
                        cd "${BACKEND_DEPLOY_PATH}/anypay"
                        echo "开始重启服务..."
                        nohup ./restart.sh > restart.log 2>&1 &

                        echo "检查服务状态..."
                        ./check.sh

                        echo "后端部署完成"
                    else
                        echo "未找到后端制品文件: ${WORKSPACE}/berabuild/artifacts/$BACKEND_ARTIFACT_NAME"
                        exit 1
                    fi

                    # 处理前端部署
                    echo "开始部署前端..."
                    if [ -n "$FRONTEND_ARTIFACT_NAME" ] && [ -f "${WORKSPACE}/berabuild/artifacts/$FRONTEND_ARTIFACT_NAME" ]; then
                        # 备份制品
                        cp "${WORKSPACE}/berabuild/artifacts/$FRONTEND_ARTIFACT_NAME" "${ARTIFACTS_BACKUP_PATH}/"

                        # 解压到目标目录
                        tar -xzf "${WORKSPACE}/berabuild/artifacts/$FRONTEND_ARTIFACT_NAME" -C "${FRONTEND_DEPLOY_PATH}"

                        echo "前端部署完成"
                    else
                        echo "未找到前端制品文件: ${WORKSPACE}/berabuild/artifacts/$FRONTEND_ARTIFACT_NAME"
                        exit 1
                    fi

                    # 清理构建产物名称文件
                    rm -f ${ARTIFACT_NAMES_FILE}
                '''
            }
        }
    }
}